local component = require("component")
local gpu = component.gpu
local image = require("image")

local function genericWrapper(args)
	local drawBuffer = args.buffer or gpu.allocateBuffer(args.x,args.y)
	local prevBuffer = gpu.getActiveBuffer()
	gpu.setActiveBuffer(drawBuffer)
	args[1](args.args)
	gpu.setActiveBuffer(prevBuffer)
	return drawBuffer
end

local function vertical_line(x)
	gpu.fill(x,2,1,9,"║")
	gpu.set(x,1,"╦")
	gpu.set(x,11,"╩")
end

local function backgroundWrapper(args)
	genericWrapper{background,args={args.selected},buffer=args.buffer,x=50,y=25}
end
local function background(args)
	local selected = args.selected

	gpu.setBackground(0x00ffff)
	gpu.setForeground(0x888800)
	gpu.fill(1,1,x,y," ")
	gpu.fill(1,1,x,1,"═")
	gpu.fill(1,11,x,1,"═")
	gpu.fill(1,2,1,9,"║")
	gpu.fill(x,2,1,9,"║")
	gpu.set(1,1,"╔")
	gpu.set(x,1,"╗")
	gpu.set(1,11,"╚")
	gpu.set(x,11,"╝")

	local names = {
		{"Флеш Рояль", 800}, 
		{"Стрит-Флеш", 50},
		{"Каре", 25},
		{"Фулл-Хаус", 9},
		{"Флеш", 6},
		{"Стрит", 4},
		{"Сет", 3},
		{"Две пары", 2},
		{"Валет и выше", 1}
	}
	for i,v in ipairs(names) do
		gpu.set(2,1+i,v[1])
		for j=1,5 do
			if j == selected then
				gpu.setForeground(0x00ffff)
				gpu.setBackground(0x888800)
			end
			local value = v[2]*j*100
			if value >= 1000 then
				gpu.set(15+(j*6),i+1,string.format("%4dK",(value//1000)))
			else
				gpu.set(15+(j*6),i+1,string.format("%5d",(value)))
			end
			if j == selected then
				gpu.setBackground(0x00ffff)
				gpu.setForeground(0x888800)
			end
		end
	end
	for i=1,5 do
		vertical_line(14+(i*6))
	end
end

local function drawCardBuffer(buffer)
end

local function drawCardsBuffer(args)
	genericBuffer{args={},buffer=args.buffer,x=50,y=25}
end
local function drawCards(args)
	local drawBuffer = args.buffer or gpu.allocateBuffer(50,25)
	local prevBuffer = gpu.getActiveBuffer()
	gpu.setActiveBuffer(drawBuffer)
	gpu.setActiveBuffer(0)
	gpu.set(1,1,card .. "")
	--for i=1,5 do
	--	gpu.bitblt(0,1+(i-1)*5,13,5,5,card)
	--end
	gpu.setActiveBuffer(prevBuffer)
	return drawBuffer
end

return {
	background = drawBufferWrapper,
	drawCards = drawCards
}
